/**
 * 课程数据管理Hook
 */

'use client';

import { useState, useEffect } from 'react';
import { CourseSchedule, Course } from '../types/course';
import LocalStorage from '../utils/localStorage';
import localStorageKeys from '../utils/localStorageKeys';
import { sanitizeCourseData } from '../data/courseData';

export interface UseCourseDataReturn {
  /** 课程表数据 */
  courseSchedule: CourseSchedule | null;
  /** 课程列表 */
  courses: Course[];
  /** 加载状态 */
  loading: boolean;
  /** 错误信息 */
  error: string | null;
  /** 重新加载数据 */
  reload: () => Promise<void>;
}

/**
 * 课程数据管理Hook
 * @returns 课程数据和相关状态
 */
export const useCourseData = (): UseCourseDataReturn => {
  const [courseSchedule, setCourseSchedule] = useState<CourseSchedule | null>(null);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const loadData = async () => {
    setLoading(true);
    setError(null);
    try {
      const useCache = LocalStorage.getItem(localStorageKeys.USE_COURSE_CACHE) === true;

      if (useCache) {
        const cachedData = LocalStorage.getItem(localStorageKeys.CACHE_COURSES) as { class_code: string; fetched_at: string; data: any } | null;

        if (cachedData) {
          const fetchedDate = new Date(cachedData.fetched_at);
          const today = new Date();
          // 如果不是同一天，则缓存失效
          if (fetchedDate.toDateString() !== today.toDateString()) {
            LocalStorage.removeItem(localStorageKeys.CACHE_COURSES);
            setCourseSchedule(null); // 清空旧数据
          } else {
            const courseData = cachedData.data;
            const newSchedule: CourseSchedule = {
              courses: courseData.courses.map((c: any) => ({ ...c, week: c.day_of_week })),
              major: courseData.class_info.class_name,
              startDate: courseData.class_info.start_date,
              semester: ''
            };
            const sanitizedData = sanitizeCourseData(newSchedule);
            setCourseSchedule(sanitizedData);
          }
        }
      } else {
        // 如果关闭缓存，则清空课程数据，等待网络请求
        setCourseSchedule(null);
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : '加载课程数据失败';
      setError(errorMessage);
      console.error('Failed to load course data:', err);
    } finally {
      setLoading(false);
    }
  };

  useEffect(() => {
    loadData();
  }, []);

  return {
    courseSchedule,
    courses: courseSchedule?.courses || [],
    loading,
    error,
    reload: loadData
  };
};
